import Emitter from "../../../Framework/Common/Emitter";
import ResMgr from "../../../Framework/Res/ResMgr";
import ModuleBase from "./ModuleBase";
import ModuleMgr from "./ModuleMgr";
import { PoolManager } from "./NodePool";
import TiledMapCtrl from "./TiledMapCtrl";

const { ccclass, property } = cc._decorator;
@ccclass
export default class BlastLayer extends ModuleBase {
    //存储贴图资源
    private _atlas: cc.SpriteAtlas = null;
    private _tiledMapCtrl: TiledMapCtrl = null;
    //获取水花
    //创建一个对象，将方向和对应的水花进行配对
    private _objDir = {
        center: "blastC_0",
        up: "blastU_0_0",
        down: "blastD_0_0",
        left: "blastL_0_0",
        right: "blastR_0_0"
    }
    onInit(...rest: any[]): void {

        this._tiledMapCtrl = ModuleMgr.instance.getModule<TiledMapCtrl>("TiledMapCtrl");
        //注册消息
        Emitter.instance.on("Blast", this, this.createBlast);
    }

    createBlast(mapDir: Map<string, Map<string, cc.Vec2>[]>) {
        //从对象池中获取水花
        mapDir.forEach(async (arrTile: Map<string, cc.Vec2>[], strDir: string, mapDir: Map<string, Map<string, cc.Vec2>[]>) => {
            for (let mapTile of arrTile) {
                let arrBlastName: string[] = [];
                arrBlastName = Array.from(mapTile.keys());
                let blastName = arrBlastName[0];
                //获取水花节点
                let pool = PoolManager.instance.getNodePool(blastName);
                let blastN = pool.getNode();
                blastN.parent = this._tiledMapCtrl.node;
                let tiledPos: cc.Vec2 = mapTile.get(blastName);
                let pos = this._tiledMapCtrl.getPoxiByTiledPos(tiledPos);
                blastN.setPosition(cc.v3(pos));
                //先通过方向获取水花的名字
                let otherDirblastName = this._objDir[strDir];
                //别的方向,需要还精灵帧
                let spriteComp = blastN.getComponent(cc.Sprite);
                //获取贴图资源
                this._atlas = ResMgr.instance.getRes<cc.SpriteAtlas>("AtlasRes", "blast");
                let newSpriteFrame = this._atlas.getSpriteFrame(otherDirblastName);
                spriteComp.spriteFrame = newSpriteFrame;
                //将水花进行回收
                this.scheduleOnce(() => {
                    PoolManager.instance.getNodePool(arrBlastName[0]).putNode(blastN);
                }, 0.3);
            }
        });
    }
}